package com.nf.practice.downloadFile;

import org.junit.platform.commons.util.StringUtils;

import java.io.File;

// 批量修改文件名
public class BatchRenameFile {

    public static void main(String[] args) {
        File directory = new File("C:/file/D类");
        renameFiles(directory);
    }

    private static void renameFiles(File directory) {
        // 以B开头,以非.jpg结尾
        String regEx1 = "^B.*[^jpg]$";
        // 以K开头,以非.pdf结尾
        String regEx2 = "^K.*[^pdf]$";

        File[] subdirectories = directory.listFiles();
        if (subdirectories != null) {
            for (File subdirectory : subdirectories) {
                if (subdirectory.isDirectory()) {
                    renameFiles(subdirectory); // 递归处理子文件夹
                } else {
                    String newFileName = "";
                    String fileName = subdirectory.getName();
                    if (fileName.matches(regEx1)) {
                        newFileName = fileName + ".jpg"; // 新文件名
                    } else if (fileName.matches(regEx2)) {
                        newFileName = fileName + ".pdf"; // 新文件名
                    }
                    if (StringUtils.isNotBlank(newFileName)) {
                        File newFile = new File(subdirectory.getParent(), newFileName); // 新文件路径
                        try {
                            if (subdirectory.renameTo(newFile)) { // 重命名文件
                                System.out.println("文件 " + fileName + " 已成功重命名 " + newFileName);
                            } else {
                                System.out.println("无法重命名文件 " + fileName);
                            }
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

}
